#include <iostream>
#include "cunchuti/kongzhi/kongzhi_impl/kongzhi_impl1.h"
#include "wenjianceng/kongzhi/kongzhi_impl/Wenjiankongzhiimpl1.h"
#include <fstream>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include "cunchuti/Cunchutistart.h"
#include "server/server.h"
#include "jiekouceng/Jiekou.h"
using namespace std;

int shuchu(FILE *file, struct tm *ptm, const char *str) {
	int a = fprintf(file, "%d年%d月%d日%d:%d:%d    %s\n", ptm->tm_year + 1900,
			ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min,
			ptm->tm_sec, str);
	fflush(file);
	return a;
}
struct tm* shijian() {
	time_t now;
	time(&now);
	return localtime(&now);
}

int main(int argc, char *argv[]) {
	try {
		if (strcmp(argv[1], "-us") == 0) {
			Cunchuti_start(25600);
			Cunchuti_kongzhi ck;
			Jiekou jk(&ck);
			cout << jk.get_used_size() << endl;
		} else if (strcmp(argv[1], "-c") == 0) {
			unsigned long len = 0;
			if (argc < 3) {
				len = 25600;
			} else {
				len = atol(argv[2]);
			}
			Cunchuti_start st(len);
		}else if (strcmp(argv[1], "-ub") == 0) {
			Cunchuti_start(25600);
			Cunchuti_kongzhi ck;
			Jiekou jk(&ck);
			cout << jk.get_used_baifenbi() <<"%"<< endl;
		} else if (strcmp(argv[1], "-as") == 0) {
			Cunchuti_start(25600);
			Cunchuti_kongzhi ck;
			Jiekou jk(&ck);
			cout << jk.get_all_size() << endl;
		} else if (strcmp(argv[1], "-ac") == 0) {
			Cunchuti_start(25600);
			Cunchuti_kongzhi ck;
			Jiekou jk(&ck);
			jk.add_cunchuti(string(argv[2]));
		} else if (strcmp(argv[1], "-cf") == 0) {
			Cunchuti_start(25600);
			Cunchuti_kongzhi ck;
			Jiekou jk(&ck);
			TF_file().create_file(string(argv[2]), atol(argv[3]));
		} else if (strcmp(argv[1], "-s") == 0) {
			if (daemon(1, 0) < 0) {
				cout << "守護進程開啓失敗" << endl;
			}
			FILE *file = fopen(TMG, "a");
			shuchu(file, shijian(), "服务已开启");
			fclose(file);
			Cunchuti_start(25600);
			server se;
			se.server_start();
		} else if (strcmp(argv[1], "--help") == 0) {
			cout << "-c [size] 初始化一個size大小的存儲體文件，未指定size則按100M大小創建（僅在默認存儲體文件未創建時生效）" << endl;
			cout << "-us 輸出已用空間大小" << endl;
			cout << "-as 輸出全部空間大小" << endl;
			cout << "-ub 輸出已用空間百分比" << endl;
			cout << "-ac [path] 將path路徑的文件作爲存儲體文件加入系統中" << endl;
			cout << "-cf [path] [size] 創建path文件，大小爲size（實際大小爲size*4096）"
					<< endl;
			cout << "-s 開啓服務" << endl;
		}
	} catch (char const *err) {
		FILE *file = fopen(TMG, "a");
		shuchu(file, shijian(), err);
		fclose(file);
	}

	return 0;
}

